<?php
/**
 * 轿辰会API接口
 */
namespace Api\Controller;
use Common\Model\CouponModel;
use Common\Model\LogModel;
use Common\Model\OtherSystem\jch;
use Common\Model\UserModel;
use Common\Model\UtilsModel;
use Common\Model\WeixinModel;
use Common\Model\WeixinTicketModel;
use Think\Controller;
class HxhController extends Controller {
    const SIGN_USEFULL_TIME=600;//签名有效期，10分钟

    const SUCCESS   =0;//成功
    const FAILURE   =1;//失败

    public function index(){
        $this->show('红旭会接口','utf-8');
    }

    private $dataSuccess=array(
        'status'=>self::SUCCESS,
        'msg'=>'success'
    );

    private $dataFailure=array(
        'status'=>self::FAILURE,
        'msg'=>'failure'
    );


    private $param=null;
    function _initialize(){
        if(IS_CLI){
           if(!$this->checkSafe_cli()){
                $this->ajaxReturn($this->dataFailure);
           }
        }elseif(IS_CGI){
            if(!$this->checkSafe_cgi()){
                $this->ajaxReturn($this->dataFailure);
            }
        }
       // $this->ajaxReturn($this->dataSuccess);
    }

    /**
     * 安全性检查，时效，签名  cli执行方式
     * Author: shijy
     * @return bool
     */
    private function checkSafe_cli(){
        global $argc,$argv;
        if($argc<3){
            $this->dataFailure['msg']='parameter error';
            return false;
        }

        //以下对业务参数解包，最后的$param是我们最终可用的数据键值对，形如$_POST
        parse_str(urldecode($argv[2]),$param);
        $t=$param['T'];
        $s=$param['S'];

        $now=time();
        if($t > $now){
            $this->dataFailure['msg']='wrong time';
            return false;
        }

        if($now-$t >= self::SIGN_USEFULL_TIME){
            $this->dataFailure['msg']='the sign is overdue';
            return false;
        }

        unset($param['T']);
        unset($param['S']);

        ksort($param);
        $paramStr=http_build_query($param);


        $company=COMPANY_JCH;
        $className="\\Common\\Model\\OtherSystem\\".$company;
        if(!class_exists($className)){
            return null;
        };

        $companyEngine= new $className();
        $sign=$companyEngine->mkSign($t,$paramStr);
        if(strcasecmp($s,$sign)!=0){
            $this->dataFailure['msg']='Security authentication failed';
            return false;
        }else{
            $this->param=$param;
            return true;
        }
    }
    
    /**
     * 安全性检查，时效，签名  cli执行方式
     * Author: shijy
     * @return bool
     */
    private function checkSafe_cgi(){
        $company=COMPANY_JCH;
        $className="\\Common\\Model\\OtherSystem\\".$company;
        if(!class_exists($className)){
            return null;
        };

        $actionName =ACTION_NAME;
        $timestamp  =I('get.t',0,'int');
        $s          =I('get.sg');

        $now=time();
        if($timestamp < $now-600){
            $this->dataFailure['msg']='wrong time';
            return false;
        }

        if($now-$timestamp >= self::SIGN_USEFULL_TIME){
            $this->dataFailure['msg']='the sign is overdue';
            return false;
        }

        $companyEngine= new $className();
        $sign=$companyEngine->mkSign($actionName,$timestamp,$_POST);
        if(strcasecmp($s,$sign)!=0){


            $temp=array();
            $temp['sk']    = 'hzxhbyg4gjjyyqqkkdgzsmshjgzayjjj1000hzgdbuytszs800hb';
            $temp['act']   = $actionName;
            $temp['t']     = $timestamp;
            if(!is_null($_POST)){
                $temp['data']  =md5(json_encode($_POST));
            }
            ksort($temp);
            $paramStr=http_build_query($temp);
            $this->dataFailure['param']=var_export($_POST,1);
            $this->dataFailure['str']=$paramStr;
            $this->dataFailure['msg']='Security authentication failed';
            return false;
        }else{
            $this->param=$_POST;
            return true;
        }
    }

    /**
     * 传递用户信息
     * Author: shijy
     */
    public function user(){
        $rawData=$_POST['data'];

        $logFile='user';
        LogModel::dailyLog($logFile,$rawData);

        $data=json_decode($rawData,1);
        if(count($data)==0){
            $this->dataFailure['msg']='no change';
            $this->ajaxReturn($this->dataFailure);
        }

        $vals=array();
        foreach ($data as $one){
            $address=UtilsModel::formatAddress($one['address']);
            $tmp=array(
                'uid'=>$one['user_id'],
                'nickname'=>$one['nickname'],
                'realName'=>$one['name'],
                'bindPhone'=>$one['phone_num'],
                'sex'=>$one['sex'],
                'regTime'=>strtotime($one['create_time']),
                'point'=>$one['credit'],
                'money'=>$one['rmb']/100,
                'birthday'=>$one['birthday'],
                'address'=>$address['newAddress'],
                'province'=>$address['province'],
                'city'=>$address['city'],
                'district'=>$address['district']
            );
            $vals[]="('".implode("','",$tmp)."')";
        }
        $fields='`'.implode('`,`',array_keys($tmp)).'`';

        $values=implode(',',$vals);
        $sql="insert into u_user_base({$fields}) values {$values} 
                    on duplicate key update nickname=values(nickname),realName=values(realName),bindPhone=values(bindPhone),sex=values(sex),
                    regTime=values(regTime),point=values(point),money=values(money),birthday=values(birthday)
                    ,address=values(address),province=values(province),city=values(city),district=values(district)";


        M('u_user_base',null,DB_MAIN_CFG)->execute($sql);

        $this->ajaxReturn($this->dataSuccess);
    }


    /**
     * 发放卡券
     * Author: shijy
     */
    public function issueCoupon(){
        $rawData=$_POST['data'];
        $logFile='issueCoupon';
        LogModel::dailyLog($logFile,$rawData);
        $dataARR=json_decode($rawData,1);

        $now=time();
        $addDataS=array();
        $newData=array();
        foreach($dataARR as $data) {
            $newData['tid'] = $data['mid'];
            $newData['couponType'] = $data['type'];
            $newData['money'] = $data['money'] / 100;
            $newData['couponTitle'] = $data['name'];
            $newData['uid'] = $data['user_id'];
            $newData['beginTimestamp'] = $data['beginTimestamp'];
            $newData['endTimestamp'] = $data['endTimestamp'];
            $newData['intro'] = $data['intro'];
            $newData['store'] = $data['4s_name'];
            $newData['img'] = $data['img'];
            $newData['bindInfo'] = $data['carNumber'];

            $newData['addTime'] = $now;
            $newData['updateTime'] = 0;
            $newData['couponFrom'] = COMPANY_JCH;
            $newData['couponStatus'] = CouponModel::CODE_STATUS_RECEIVED;
            $addDataS[]=$newData;
        }
        M('third_coupon',null,DB_MAIN_CFG)->addAll($addDataS);

        $this->ajaxReturn($this->dataSuccess);
    }

    /**
     * 核销卡券
     * Author: shijy
     */
    public function consumeCoupon(){
        $rawData=$_POST['data'];
        $logFile='consumeCoupon';
        LogModel::dailyLog($logFile,$rawData);

        $data=json_decode($rawData,1);
        if (count($data)>0) {
            $condition = array();
            foreach ($data as $one) {
                $condition[] = " (tid='{$one['mid']}' and couponType='{$one['type']}') ";
            }
            $where = implode(' or ', $condition);
            $updateData = array(
                'couponStatus' => CouponModel::CODE_STATUS_USED,
                'updateTime' => time()
            );
            M('third_coupon', null, DB_MAIN_CFG)->where($where)->save($updateData);
        }
        $this->ajaxReturn($this->dataSuccess);
    }

    //用户合并
    public function userMerge(){
        $rawData=$_POST['data'];
        $logFile='userMerge';
        LogModel::dailyLog($logFile,$rawData);
        $data=json_decode($rawData,1);
        $fromUid    = $data['f_uid'];
        $toUid      = $data['t_uid'];
        M('third_coupon',null,DB_MAIN_CFG)->where("uid={$fromUid}")->setField('uid',$toUid);
        M('card_code',null,DB_MAIN_CFG)->where("uid={$fromUid}")->setField('uid',$toUid);
        $this->ajaxReturn($this->dataSuccess);
    }


    /**
     * 可变数值累积型属性变化通知
     * Author: shijy
     */
    public function val(){
        $rawData=$_POST['data'];
        $now=time();
        $logFile='val';
        LogModel::dailyLog($logFile,$rawData);

        $data=json_decode($rawData,1);
        if(count($data)==0){
            $this->dataFailure['msg']='no change';
            $this->ajaxReturn($this->dataFailure);
        }

        $pointLog=array();
        $EXPLog=array();
        $MoneyLog=array();

        foreach ($data as $one){
            $tmp=array(
                'uid'=>$one['uid'],
                'addOrReduce'=>$one['addOrReduce'],
                'act'=>jch::actionSwitch_Jch_StarJoy($one['action']),
                'changeVal'=>$one['changeVal'],
                'desc'=>$one['miaoshu'],
                'addTime'=>$now,
                'outerId'=>$one['log_id']
            );
            switch($one['addOrReduce']+0){
                case VAL_REDUCE:
                    $tmp['finalVal']=$one['originVal']-$one['changeVal'];
                    break;
                case VAL_ADD:
                    $tmp['finalVal']=$one['originVal']+$one['changeVal'];
                    break;
                default:
                    LogModel::dailyLog($logFile,'增加还是减少不确定！'.$one['addOrReduce']);
                    continue;
                    break;
            }

            switch ($one['elementType']+0){
                case ELEMENT_TYPE_POINT:
                    $pointLog[]=$tmp;
                    break;
                case ELEMENT_TYPE_MONEY:
                    $MoneyLog[]=$tmp;
                    break;
                case ELEMENT_TYPE_EXP:
                    $EXPLog[]=$tmp;
                    break;
            }
        }
        
        if(count($pointLog)>0){
            $ret=M('u_point_log',null,DB_MAIN_CFG)->addAll($pointLog);
            LogModel::dailyLog($logFile,'point日志添加'.$ret);
        }

        if(count($EXPLog)>0){
            $ret=M('u_exp_log',null,DB_MAIN_CFG)->addAll($EXPLog);
            LogModel::dailyLog($logFile,'exp日志添加'.$ret);
        }

        if(count($MoneyLog)>0){
            $ret=M('u_money_log',null,DB_MAIN_CFG)->addAll($MoneyLog);
            LogModel::dailyLog($logFile,'money日志添加'.$ret);
        }

        $this->ajaxReturn($this->dataSuccess);
    }


    /**
     *接收来自聚星的微信消息转发总入口
     * Author: shijy
     */
    public function wx_receive(){
        $rawData=$_POST['data'];
        $logFile='wxReceive';
        LogModel::dailyLog($logFile,$rawData);
        $tmpStr=str_replace("\n",'',$rawData);
        $tmpStr=str_replace("\/",'/',$tmpStr);
        $tmpStr=str_replace('"','',$tmpStr);

        $xmlObj=simplexml_load_string($tmpStr);
        $val=array();
        foreach($xmlObj as $k=>$v){
            $val[$k]=$xmlObj->$k.'';
        }
        switch(strtolower($val['Event'])){
            case 'card_pass_check':
                break;
            case 'card_not_pass_check':
                break;
            case 'user_get_card':
                break;
            case 'user_del_card':
                break;
            case 'user_consume_card':
                break;
            case 'card_sku_remind':
                break;
            default:
                LogModel::dailyLog($logFile,'非预定事件'.$val['Event']);
                return;
                break;
        }
        $action=$val['Event'];
        $this->$action($val);

    }

    /**
     * 微信事件推送，卡券审核通过
     * Author: shijy
     * @param $param
     */
    private function card_pass_check($param){
        M('card_base_info',NULL,DB_MAIN_CFG)->where("weixinId='{$param['CardId']}'")
            ->setField('weixinCheck',WeixinTicketModel::WEIXIN_CHECK_PASS);

        $logFile='card_pass_check';
        LogModel::dailyLog($logFile,$param);

    }



    /**
     * 微信事件推送，卡券审核未通过
     * Author: shijy
     * @param $param
     */
    private function card_not_pass_check($param){
        M('card_base_info',NULL,DB_MAIN_CFG)->where("weixinId='{$param['CardId']}'")->setField('weixinCheck',WeixinTicketModel::WEIXIN_CHECK_UNPASS);
        $logFile='card_not_pass_check';
        LogModel::dailyLog($logFile,$param);
    }


    /**
     * 用户领取卡券
     * Author: shijy
     * @param $param
     */
    private function user_get_card($param){
        $uReturn =UserModel::getUidByWeixinOpenID($param['FromUserName']);
        if($uReturn['status']!=0){
            $this->ajaxReturn($uReturn);
        }
        $uid=$uReturn['uid'];

        $cReturn =CouponModel::getCardIDByWxCardID($param['CardId']);
        if($cReturn['status']!=0){
            $this->ajaxReturn($cReturn);
        }
        $cardID=$cReturn['cardID'];
        $upData=array(
            'uid'=>$uid,
            'status'=>CouponModel::CODE_STATUS_RECEIVED,
            'receiveTimestamp'=>time()
        );

        $where="code='{$param['UserCardCode']}' and cardId={$cardID} and status=".CouponModel::CODE_STATUS_SEND;
        M('card_code',null,DB_MAIN_CFG)->where($where)->save($upData);
    }


    /**
     * 用户删除卡券
     * Author: shijy
     * @param $param
     */
    private function user_del_card($param){
        $uReturn =UserModel::getUidByWeixinOpenID($param['FromUserName']);
        if($uReturn['status']!=0){
            $this->ajaxReturn($uReturn);
        }
        $uid=$uReturn['uid'];

        $cReturn =CouponModel::getCardIDByWxCardID($param['CardId']);
        if($cReturn['status']!=0){
            $this->ajaxReturn($cReturn);
        }
        $cardID=$cReturn['cardID'];
        M('card_code',null,DB_MAIN_CFG)->where("code='{$param['UserCardCode']}' and cardId={$cardID}")->setField('status',CouponModel::CODE_STATUS_DELETE);

        M('card_base_info',null,DB_MAIN_CFG)->where('id='.$cardID)->setInc('delNum');
    }

    /**
     * 核销卡券
     * Author: shijy
     */
    private function user_consume_card($param){
        $uReturn =UserModel::getUidByWeixinOpenID($param['FromUserName']);
        if($uReturn['status']!=0){
            $this->ajaxReturn($uReturn);
        }
        $uid=$uReturn['uid'];

        $cReturn =CouponModel::getCardIDByWxCardID($param['CardId']);
        if($cReturn['status']!=0){
            $this->ajaxReturn($cReturn);
        }
        $cardID=$cReturn['cardID'];
        $upData=array(
            'uid'=>$uid,
            'status'=>CouponModel::CODE_STATUS_USED,
            'consumeTime'=>time()
        );
        M('card_code',null,DB_MAIN_CFG)->where("code='{$param['UserCardCode']}' and cardId={$cardID}")->save($upData);
        //库存修改
        M('card_base_info',null,DB_MAIN_CFG)->where('id='.$cardID)->setInc('consumeNum');
    }


    /**
     * 卡券库存报警
     * Author: shijy
     * @param $param
     */
    private function card_sku_remind($param){
        M('card_base_info',NULL,DB_MAIN_CFG)->where("weixinId='{$param['CardId']}'")->setField('weixinStockRemind',1);
    }
}